package com.xmtlxx.common.utils;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * @author Administrator
 */
public class EncryptionProcessor {
    public static void process(Object obj) throws Exception {
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            if (field.isAnnotationPresent(EncryptField.class)) {
                field.setAccessible(true);
                Object value = field.get(obj);
                if (value != null && value instanceof String) {
                    EncryptField encryptField = field.getAnnotation(EncryptField.class);
                    String encryptedValue = EncryptUtil.getAesKey((String)value, encryptField.algorithm());
                    field.set(obj, encryptedValue);
                }
            }
        }
    }

    public static void processBatch(Object[] objects) {
        Arrays.stream(objects).forEach(obj -> {
            try {
                process(obj);
            } catch (Exception e) {
                throw new RuntimeException("加密处理失败", e);
            }
        });
    }

    public static void decryptProcess(Object obj) throws Exception {
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            if (field.isAnnotationPresent(EncryptField.class)) {
                field.setAccessible(true);
                Object value = field.get(obj);
                if (value != null && value instanceof String) {
                    EncryptField encryptField = field.getAnnotation(EncryptField.class);
                    String encryptedValue = EncryptUtil.decryptAesKey((String)value, encryptField.algorithm());
                    field.set(obj, encryptedValue);
                }
            }
        }
    }

    public static void decryptProcessBatch(Object[] objects) {
        Arrays.stream(objects).forEach(obj -> {
            try {
                decryptProcess(obj);
            } catch (Exception e) {
                throw new RuntimeException("解密处理失败", e);
            }
        });
    }
}
